package com.funteam.funmask;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	
	private Handler mHandler; // for touching two times back key to finish the APP
	private boolean mFlag = false; // for finishing the APP
	
	private ImageButton mIbArMask, mIbFunMask;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		mIbArMask = (ImageButton) findViewById(R.id.ib_armask);
		mIbArMask.setOnClickListener(this);
		mIbFunMask = (ImageButton) findViewById(R.id.ib_funmask);
		mIbFunMask.setOnClickListener(this);
		
		mHandler = new Handler() {
			public void handlerMessage(Message msg) {
				if (msg.what == 0) {
					mFlag = false;
				}
			}
		};
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.ib_armask:
			Intent intentAr = new Intent (this, ArMaskActivity.class);
			startActivity(intentAr);
			break;
		case R.id.ib_funmask:
			Intent intentFun = new Intent(this, FunMaskActivity.class);
			startActivity(intentFun);
			break;
		}
	}
	
	/*
	 * check the flag value, then steal the keyevent when flag value is true, if
	 * push the back key during 2sec, finish the activity
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!mFlag) {
				Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();
				mFlag = true;
				mHandler.sendEmptyMessageDelayed(0, 2000); //during 2sec, put twice -> finish the APP
				return false;
			} else {
				moveTaskToBack(true);

				finish();
				// process killing
				android.os.Process.killProcess(android.os.Process.myPid());
				onDestroy();
			}

		}
		return super.onKeyDown(keyCode, event);

	}

}
